package com.htfyun.ft;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

import com.htfyun.ft.common.SettingsUtils;
import com.htfyun.ft.config.FTProperty;
import com.htfyun.ft.fragment.factory.FactoryBaseFragment;
import com.htfyun.ft.fragment.factory.FactoryTestItemsEnum;
import com.htfyun.ft.utils.DebugLog;
import com.htfyun.ft.viewmodel.FTAction;
import com.htfyun.ft.viewmodel.ViewModelFT;
import com.htfyun.ft.viewmodel.ViewModelFTGot;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

public class FTActivity extends BaseActivity {

    private Context mContext;

    private View btnAutoPrevious;
    private Fragment currentFragment;

    private Map<FactoryTestItemsEnum, Fragment> fragmentMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ft);

        mContext = this;

        initFragmentMap();

        initViewModelFT();

        switchFactoryTestItemsEnum(FactoryTestItemsEnum.main);

        btnAutoPrevious = findViewById(R.id.btnAutoPrevious);
        btnAutoPrevious.setVisibility(View.GONE);
        btnAutoPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FactoryTestItemsEnum itemsEnum = FactoryTestItemsEnum.getItemEnumByFragment(currentFragment);
                List<FactoryTestItemsEnum> itemsEnumList = getFactoryTestItemsEnumList();
                if (itemsEnumList != null && itemsEnum != null) {
                    int index = itemsEnumList.indexOf(itemsEnum);
                    index--;
                    if (index >= 0) {
                        switchFactoryTestItemsEnum(itemsEnumList.get(index));
                    } else {
                        switchFactoryTestItemsEnum(FactoryTestItemsEnum.main);
                        viewModelFT.setAutoTest(false);
                    }
                }

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        FTProperty.setHtfyunFTEnabled(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (currentFragment instanceof FactoryBaseFragment) {
            ((FactoryBaseFragment) currentFragment).dispatchTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if (currentFragment instanceof FactoryBaseFragment) {
            return ((FactoryBaseFragment) currentFragment).onKeyUp(keyCode, event);
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (currentFragment instanceof FactoryBaseFragment) {
            return ((FactoryBaseFragment) currentFragment).onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }

    private ViewModelFT viewModelFT;
    private void initViewModelFT() {

        if (viewModelFT == null) {
            viewModelFT = ViewModelFTGot.getViewModel(mContext);
        }

        viewModelFT.getClickedItem().observe(this, new Observer<FactoryTestItemsEnum>() {
            @Override
            public void onChanged(FactoryTestItemsEnum factoryTestItemsEnum) {

                if (isAutoTest()) {
                    FactoryTestItemsEnum itemsEnum = FactoryTestItemsEnum.getItemEnumByFragment(currentFragment);
                    List<FactoryTestItemsEnum> itemsEnumList = getFactoryTestItemsEnumList();
                    if (itemsEnumList != null && itemsEnum != null) {

                        int index = itemsEnumList.indexOf(itemsEnum);

                        index++;
                        if (index < itemsEnumList.size()) {
                            switchFactoryTestItemsEnum(itemsEnumList.get(index));
                        } else {
                            switchFactoryTestItemsEnum(FactoryTestItemsEnum.main);
                            viewModelFT.setAutoTest(false);
                        }
                    }
                } else {

                    switchFactoryTestItemsEnum(factoryTestItemsEnum);
                }

            }
        });

        viewModelFT.getFTAction().observe(this, new Observer<FTAction>() {
            @Override
            public void onChanged(FTAction ftAction) {
                switch (ftAction) {
                    case finishMe:
                        ActivityCompat.finishAfterTransition(FTActivity.this);
                        break;
                }
            }
        });

        viewModelFT.getAutoTest().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
//                btnAutoPrevious.setVisibility(aBoolean ? View.VISIBLE : View.GONE);
                if (aBoolean) {
                    List<FactoryTestItemsEnum> itemsEnumList = getFactoryTestItemsEnumList();
                    if (itemsEnumList != null && !itemsEnumList.isEmpty()) {
                        switchFactoryTestItemsEnum(itemsEnumList.get(0));
                    }
                }
            }
        });
    }

    private boolean isAutoTest() {
        return (viewModelFT.getAutoTest().getValue() != null && viewModelFT.getAutoTest().getValue());
    }
    private List<FactoryTestItemsEnum> getFactoryTestItemsEnumList() {
        return viewModelFT.getFactoryTestItemsEnumList().getValue();
    }

    private void switchFactoryTestItemsEnum(FactoryTestItemsEnum itemsEnum) {
        Fragment fragment = fragmentMap.get(itemsEnum);
        if (fragment != null) {
            switchFragment(fragment);
        }

    }

    private void switchFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        if (currentFragment == null) {
            fragmentTransaction.add(R.id.container, fragment).commit();
            currentFragment = fragment;
        }
        if (currentFragment != fragment) {
            // 先判断是否被add过
            if (!fragment.isAdded()) {
                // 隐藏当前的fragment，add下一个到Activity中
                fragmentTransaction.hide(currentFragment)
                        .add(R.id.container, fragment).commit();
            } else {
                // 隐藏当前的fragment，显示下一个
                fragmentTransaction.hide(currentFragment).show(fragment)
                        .commit();
            }
            currentFragment = fragment;
        }
    }

    private void initFragmentMap() {
        for (FactoryTestItemsEnum itemsEnum : FactoryTestItemsEnum.values()) {
            if (itemsEnum.getItemFragment() != null) {
                try {
                    fragmentMap.put(itemsEnum, itemsEnum.getItemFragment().newInstance());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
